import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
import execjs


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "“人人安康”百万医疗保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 66)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["1000000"],
                # 恶性肿瘤保险金
                "cancerMedical": ["1000000"],
                # 赔付比例
                "payRate": ["100%"],
                # 年度免赔额
                "deductible": ["10000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 66)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 恶性肿瘤保险金
                "cancerMedical": ["2000000"],
                # 赔付比例
                "payRate": ["100%"],
                # 年度免赔额
                "deductible": ["10000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["generalMedical"], plan[k]["cancerMedical"],
                             plan[k]["payRate"], plan[k]["deductible"], plan[k]["expire"], plan[k]["payType"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 计算保费
    def calcPremium(self, dt=None):

        js = '''
        function CalculationFee(day,plan,index){
                var list = [
                    {
                        '0-4':[706,1556],
                        '5-10':[353,718],
                        '11-15':[209,386],
                        '16-20':[122,206],
                        '21-25':[207,433],
                        '26-30':[262,586],
                        '31-35':[350,816],
                        '36-40':[436,1116],
                        '41-45':[523,1576],
                        '46-50':[817,2288],
                        '51-55':[1008,3333],
                        '56-60':[1348,4178],
                        '61-65':[1898,5686]
                    },
                    {
                        '0-4':[778,1716],
                        '5-10':[388,796],
                        '11-15':[230,426],
                        '16-20':[136,228],
                        '21-25':[228,478],
                        '26-30':[290,648],
                        '31-35':[386,898],
                        '36-40':[480,1226],
                        '41-45':[578,1738],
                        '46-50':[898,2528],
                        '51-55':[1116,3680],
                        '56-60':[1490,4618],
                        '61-65':[1990,5970]
                    }
                ];
                for (var key in list[plan]){
                    var keySplit = key.split("-");
                    if(day>=keySplit[0]&&day<=keySplit[1]){
                       price = list[plan][key][index].toFixed(2)
                       return (price);
                       
                    }
                }
            }
        '''
        data = {
            "day": int(dt["year"]),
            "plan": "0",
            "index": "0" if dt["socialSec"] == "Y" else "1"
        }
        cxt = execjs.compile(js)
        price = cxt.call("CalculationFee", data["day"], data["plan"], data["index"])
        data = {
            "name":self.name,
            "id":dt["id"],
            "price":price
        }
        print( data )
        self.mysql.updatePrice( data )

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.calcPremium(dt)
